package com.icangya.interceptor;

import com.icangya.domain.Admin;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.icangya.Value.StaticValue.ADMIN_PROXY_SESSION;
import static com.icangya.Value.StaticValue.ADMIN_USER_SESSION;

/**
 * 代理用户操作拦截器
 */
public class ProxyLoginInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = Logger.getLogger(ProxyLoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
//        /** 拦截到用户的请求了 */
        String requestUrl = request.getRequestURL().toString();
        logger.debug("requestUrl:" + requestUrl);
        /** 判断session是否存在用户,如果存在说明用户已经登录了,应该放行 */
        Admin user = (Admin) request.getSession().getAttribute(ADMIN_PROXY_SESSION);

       if (user != null) {
            logger.debug("requestUrl:" + requestUrl + "->代理用户操作被放行！");
            //** 当前请求：每个请求是否都是一个线程   *//*
            //LoginInterceptor.addCurrentUser(user);
            return true;
        } else {
            // 重定向
            response.sendRedirect(request.getContextPath() + "/agenter/login.html");
            logger.debug("requestUrl:" + requestUrl + "->代理用户操作被拦截！");
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
       // LoginInterceptor.removeCurrentUser();
    }


   // private static ThreadLocal<AdminDO> users = new ThreadLocal<>();

//    public static void addCurrentUser(AdminDO user) {
//        if (users.get() == null) {
//            users.set(user);
//        }
//    }
//
//    public static AdminDO getCurrentUser() {
//        return users.get();
//    }
//
//    public static void removeCurrentUser() {
//        users.remove();
//    }

}
